﻿using Sprout.Core.Utils;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text;

namespace Sprout.Core.Extensions
{
    /// <summary>
    /// 扩展类
    /// </summary>
    public static class IdentityServerExtensions
    {
        /// <summary>
        /// Claims 转换成 字典
        /// </summary>
        /// <param name="claims"></param>
        /// <returns></returns>
        public static T ToEntity<T>(this IEnumerable<Claim> claims)
            where T : class, new()
        {
            if (claims != null)
            {
                var dic = new Dictionary<string, string>();
                var propertyNames = ReflectionHelper.GetPropertyNames(typeof(T));
                foreach (var claim in claims)
                {
                    if (propertyNames.Contains(claim.Type) && dic.ContainsKey(claim.Type) == false)
                    {
                        dic.Add(claim.Type, claim.Value);
                    }
                }

                return dic.ToJsonString().FromJsonString<T>();

            }
            return null;
        }
    }
}
